const executeQuery = require("./mongo_util");
const collectionName = "articles";

// 增博客  blogMdodel.addBlog(blog,onRetGot,onErrGot)
function addBlog(blog, onRetGot, onErrGot) {
    executeQuery(collectionName, (collection, callback) => {
        collection
            .insertOne(blog)
            .then((result) => {
                onRetGot(result);
                callback();
            })
            .catch((err) => {
                onErrGot(err);
                callback();
            });
    });
}

function addBlog2(blog, onRetGot, onErrGot) {
    baseQuery(
        (collection) => {
            return collection.insertOne(blog);
        },
        onRetGot,
        onErrGot
    );
}

const Blog = require("./blog_bean");
addBlog2(
    new Blog("test", "testcontent"),
    (r) => console.log("r=", r),
    (e) => console.log("e=", e)
);

// 删博客  blogMdodel.deleteBlog(bid,onRetGot,onErrGot)
function deleteBlog(bid, onRetGot, onErrGot) {
    executeQuery(collectionName, (collection, callback) => {
        collection
            .deleteOne({ id: bid })
            .then((result) => {
                onRetGot(result);
                callback();
            })
            .catch((err) => {
                onErrGot(err);
                callback();
            });
    });
}

// 改博客  blogMdodel.updateBlog(blog,onRetGot,onErrGot)
function updateBlog(blog, onRetGot, onErrGot) {
    executeQuery(collectionName, (collection, callback) => {
        // create a document that sets the plot of the movie
        const updateDoc = {
            $set: {
                title: blog.title,
                content: blog.content,
            },
        };
        collection
            .updateOne({ id: blog.id }, updateDoc)
            .then((result) => {
                onRetGot(result);
                callback();
            })
            .catch((err) => {
                onErrGot(err);
                callback();
            });
    });
}

// 查博客  blogMdodel.getBlogs(skip,limit,onRetGot,onErrGot)
function getBlogs(skip, limit, onRetGot, onErrGot) {
    executeQuery(collectionName, (collection, callback) => {
        collection
            .find()
            .skip(skip)
            .limit(limit)
            .toArray()
            .then((result) => {
                onRetGot(result);
                callback();
            })
            .catch((err) => {
                onErrGot(err);
                callback();
            });
    });
}

module.exports = {
    addBlog,
    deleteBlog,
    updateBlog,
    getBlogs,
};
